package com.sgb.kjwl.view.ui.activity.pick;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityPickInquireByLetterBinding;
import com.sgb.kjwl.di.pick.DaggerPickProjectComponent;
import com.sgb.kjwl.di.pick.PickProjectModule;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.pick.UserInquiryForTender;
import com.sgb.kjwl.view.ui.adapter.self.publish.ImageAdapter;
import com.sgb.kjwl.view.widget.pick.PickLetterListView;
import com.sgb.kjwl.viewmodel.pick.PickInquireByLetterModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.MToast;
import com.swgk.core.util.ResolutionUtil;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

public class PickInquireByLetterActivity extends AppActivity {

    @Inject
    PickInquireByLetterModel viewModel;

    private ActivityPickInquireByLetterBinding binding;
    private ImageAdapter adapter;
    private List<String> urls;
    private List<File> fileList;
    public int imgTotal;
    private int currentImgNum;
    private List<String> uploadImgList = new ArrayList<>();

    private ArrayList<UserInquiryForTender.CustomFieldListBean> customFieldListBeans = new ArrayList<>();
    private List<UserInquiryForTender.FileListBean> fileImageList = new ArrayList<>();
    private String tenderNo = "";
    private String startType = "";
    private String answerUserCompanyNo;//答复人企业编号(这条信息的所属公司)
    private String answerUserNo;//答复人编号(这条信息创建人no)
    private String markType;//租赁类别
    private String modelType;// 业务类型: 4 出租, 5 求租, 6 报价
    private String markName;//函询标题
    private String inquiryUserMemberNo;
    private String teamName = "";
    private int tenderingType = 0;
    private int[] selectPosition = new int[1];
    private List<PickSelectEntity> pickSelectEntityList = new ArrayList<>();

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPickProjectComponent.builder().appComponent(appComponent).pickProjectModule(new PickProjectModule(this)).build().inject(this);
    }

    public static void start(Context context, String tenderNo, String startType) {
        Intent intent = new Intent();
        intent.putExtra("tenderNo", tenderNo);
        intent.putExtra("startType", startType);
        intent.setClass(context, PickInquireByLetterActivity.class);
        context.startActivity(intent);
    }

    public static void start(Context context, String tenderNo, String startType, int tenderingType) {
        Intent intent = new Intent();
        intent.putExtra("tenderNo", tenderNo);
        intent.putExtra("startType", startType);
        intent.putExtra("tenderingType", tenderingType);
        intent.setClass(context, PickInquireByLetterActivity.class);
        context.startActivity(intent);
    }

    public static void start(Context context, String tenderNo, String startType, String inquiryUserMemberNo) {
        Intent intent = new Intent();
        intent.putExtra("tenderNo", tenderNo);
        intent.putExtra("startType", startType);
        intent.putExtra("inquiryUserMemberNo", inquiryUserMemberNo);
        intent.setClass(context, PickInquireByLetterActivity.class);
        context.startActivity(intent);
    }

    /**
     * 租赁-函询跳转
     *
     * @param context
     * @param tenderNo
     * @param startType
     * @param answerUserCompanyNo
     * @param answerUserNo
     * @param markType            模块类型:1机械， 2 设备，3车辆，4 房产，5土地，6工厂，7农机
     * @param markName            业务标题
     * @param modelType           业务类型: 4 出租, 5 求租, 6 报价
     */
    public static void startLease(Context context, String tenderNo, String startType, String answerUserCompanyNo, String answerUserNo, String markType, String markName, String modelType) {
        Intent intent = new Intent();
        intent.putExtra("tenderNo", tenderNo);
        intent.putExtra("startType", startType);
        intent.putExtra("answerUserCompanyNo", answerUserCompanyNo);
        intent.putExtra("answerUserNo", answerUserNo);
        intent.putExtra("markType", markType);
        intent.putExtra("markName", markName);
        intent.putExtra("modelType", modelType);
        intent.setClass(context, PickInquireByLetterActivity.class);
        context.startActivity(intent);
    }

    public static void start(Context context, String tenderNo, String startType, String answerUserCompanyNo, String answerUserNo, String markType) {
        Intent intent = new Intent();
        intent.putExtra("tenderNo", tenderNo);
        intent.putExtra("startType", startType);
        intent.putExtra("answerUserCompanyNo", answerUserCompanyNo);
        intent.putExtra("answerUserNo", answerUserNo);
        intent.putExtra("markType", markType);
        intent.setClass(context, PickInquireByLetterActivity.class);
        context.startActivity(intent);
    }

    public static void start(Context context, String tenderNo, String startType, String answerUserCompanyNo, String answerUserNo, String markType, String teamName) {
        Intent intent = new Intent();
        intent.putExtra("tenderNo", tenderNo);
        intent.putExtra("startType", startType);
        intent.putExtra("teamName", teamName);
        intent.putExtra("markType", markType);//模块的类型：1 工队 ；2 工程 3：招工用工 4 ：工种报价
        intent.setClass(context, PickInquireByLetterActivity.class);
        context.startActivity(intent);
    }

    /**
     * 打开此activity
     *
     * @param context             上下文
     * @param tenderNo
     * @param startType
     * @param answerUserCompanyNo
     * @param answerUserNo
     * @param markType
     * @param teamName
     * @param name
     */
    public static void start(Context context, String tenderNo, String startType, String answerUserCompanyNo, String answerUserNo, String markType, String teamName, String name) {
        Intent intent = new Intent();
        intent.putExtra("tenderNo", tenderNo);
        intent.putExtra("startType", startType);
        intent.putExtra("teamName", teamName);
        intent.putExtra("markType", markType);//模块的类型：1 工队 ；2 工程 3：招工用工 4 ：工种报价
        intent.putExtra("name", name);
        intent.setClass(context, PickInquireByLetterActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_pick_inquire_by_letter);
        binding.setViewModel(viewModel);
        binding.include.titleView.setText("发起函询");
        binding.include.ivBack.setOnClickListener(this);
        binding.ivAddAns.setOnClickListener(this);
        binding.tvSubmit.setOnClickListener(this);
        binding.ivDel.setOnClickListener(this);
        initExtra();
    }

    private void initExtra() {
        tenderNo = getIntent().getStringExtra("tenderNo");
        startType = getIntent().getStringExtra("startType");
        answerUserCompanyNo = getIntent().getStringExtra("answerUserCompanyNo");
        answerUserNo = getIntent().getStringExtra("answerUserNo");
        markType = getIntent().getStringExtra("markType");
        inquiryUserMemberNo = getIntent().getStringExtra("inquiryUserMemberNo");
        teamName = getIntent().getStringExtra("teamName");
        tenderingType = getIntent().getIntExtra("tenderingType", 0);

        String name = getIntent().getStringExtra("name");
        markName = getIntent().getStringExtra("markName");
        modelType = getIntent().getStringExtra("modelType");

        binding.ivAddAns.setVisibility(View.INVISIBLE);
        binding.ivAddAnsAddField.setVisibility(View.VISIBLE);

        if (tenderingType > 0) {   //招标有函询类型
            viewModel.tenderInquiryType(tenderingType);
            binding.linInquireByLetter.setVisibility(View.VISIBLE);
            binding.typeList.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        binding.tvNum.setText(adapter.getFileList().size() + " / 5");
    }

    @Override
    protected void init() {
        urls = new ArrayList<>();
        fileList = new ArrayList<>();
        adapter = new ImageAdapter(this, null, null, 5);
        binding.recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        binding.recyclerView.setAdapter(adapter);

        binding.ivAddAns.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (binding.rootLayout.getChildCount() < 5) {
                    if (binding.rootLayout.getChildCount() > 0) {
                        if (checkItemInput()) {
                            binding.ivAddAns.setImageResource(R.mipmap.add_ans);
                            PickLetterListView pickDetailListView = new PickLetterListView(PickInquireByLetterActivity.this);
                            binding.rootLayout.addView(pickDetailListView);
                            pickDetailListView.setItemChildCLickListener(new PickLetterListView.ItemChildCLickListener() {
                                @Override
                                public void deletePos() {
                                    binding.rootLayout.removeView(pickDetailListView);
                                }
                            });
                        }
                    } else {
                        binding.ivAddAns.setImageResource(R.mipmap.add_ans);
                        PickLetterListView pickDetailListView = new PickLetterListView(PickInquireByLetterActivity.this);
                        binding.rootLayout.addView(pickDetailListView);
                        pickDetailListView.setItemChildCLickListener(new PickLetterListView.ItemChildCLickListener() {
                            @Override
                            public void deletePos() {
                                binding.rootLayout.removeView(pickDetailListView);
                            }
                        });
                    }

                } else {
                    MToast.showLongToast(getApplicationContext(), "最多添加5条");
                }
            }
        });

        binding.ivAddAnsAddField.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.rootLayout.getChildCount() < 5) {
                    if (binding.rootLayout.getChildCount() > 0) {
                        if (checkItemInput()) {
                            binding.ivAddAns.setImageResource(R.mipmap.add_ans);
                            PickLetterListView pickDetailListView = new PickLetterListView(PickInquireByLetterActivity.this);
                            binding.rootLayout.addView(pickDetailListView);
                            pickDetailListView.setItemChildCLickListener(new PickLetterListView.ItemChildCLickListener() {
                                @Override
                                public void deletePos() {
                                    binding.rootLayout.removeView(pickDetailListView);
                                }
                            });
                        }
                    } else {
                        binding.ivAddAns.setImageResource(R.mipmap.add_ans);
                        PickLetterListView pickDetailListView = new PickLetterListView(PickInquireByLetterActivity.this);
                        binding.rootLayout.addView(pickDetailListView);
                        pickDetailListView.setItemChildCLickListener(new PickLetterListView.ItemChildCLickListener() {
                            @Override
                            public void deletePos() {
                                binding.rootLayout.removeView(pickDetailListView);
                            }
                        });
                    }

                } else {
                    MToast.showLongToast(getApplicationContext(), "最多添加5条");
                }
            }
        });


    }

    public void setInquiryType(List<PickSelectEntity> data) {
        if (data == null || data.size() == 0) {
            return;
        }
        pickSelectEntityList = data;
        selectPosition[0] = 0;
        final LayoutInflater mInflater = LayoutInflater.from(PickInquireByLetterActivity.this);
        TagAdapter tagAdapter = new TagAdapter<PickSelectEntity>(data) {
            @Override
            public View getView(com.zhy.view.flowlayout.FlowLayout parent, int position, PickSelectEntity pickSelectEntity) {
                LinearLayout layout = (LinearLayout) mInflater.inflate(R.layout.item_pick_inquire_by_letter, binding.typeList, false);
                TextView tv = layout.findViewById(R.id.name);
                int width = ResolutionUtil.getScreenWidth(PickInquireByLetterActivity.this) - ResolutionUtil.dp2px(getActivity(), 75);
                tv.setMinWidth(width / 4);
                tv.setText(pickSelectEntity.getProjectscale());
                if (selectPosition[0] >= 0) {
                    if (position == selectPosition[0]) {
                        tv.setBackgroundResource(R.drawable.corner_red_2_bg);
                        tv.setTextColor(getResources().getColor(R.color.white));
                    } else {
                        tv.setBackgroundResource(R.drawable.corner_ededed_bg);
                        tv.setTextColor(getResources().getColor(R.color.color_666666));
                    }
                }
                return layout;
            }
        };
        binding.typeList.setAdapter(tagAdapter);
        binding.typeList.setMaxSelectCount(1);
        binding.typeList.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, com.zhy.view.flowlayout.FlowLayout parent) {
                selectPosition[0] = position;
                tagAdapter.notifyDataChanged();
                return false;
            }
        });
    }

    private boolean checkItemInput() {
        for (int i = 0; i < binding.rootLayout.getChildCount(); i++) {
            PickLetterListView pickLetterListView = (PickLetterListView) binding.rootLayout.getChildAt(i);
            if (pickLetterListView.getViewContent()) {
                MToast.showLongToast(getApplicationContext(), "有新增的标题和内容未填写");
                return false;
            }
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_submit:
                if (TextUtils.isEmpty(binding.cfkEdit.getEditContent()) || binding.cfkEdit.getEditContent().length() < 5) {
                    MToast.showLongToast(getApplicationContext(), "疑问事项请输入最少5个字，最多200字");
                    return;
                }
                if (!checkItemInput()) {
                    return;
                }
                if (adapter.getFileList().size() != 0) {
                    uploadImgList.clear();
                    imgTotal = adapter.getFileList().size();
                    viewModel.uploadMutiFileModel(adapter.getFileList().get(currentImgNum), 0, currentImgNum + 1);
                } else {
                    uploadImgSuccess(adapter.getUrls(), 1);
                }
                break;
            case R.id.iv_del:
                binding.cfkTitle.setEditContent("");
                break;
        }
    }

    private void uploadImgSuccess(List<String> urls, int type) {
        //拼接图片url
        for (int i = 0; i < urls.size(); i++) {
            UserInquiryForTender.FileListBean fileListBean = new UserInquiryForTender.FileListBean();
            int picI = i + 1;
            fileListBean.setName("第" + picI + "张图片");
            fileListBean.setFileUrl(urls.get(i));
            if (type == 0) {
                fileImageList.add(fileListBean);
            }
        }
        for (int i = 0; i < binding.rootLayout.getChildCount(); i++) {
            PickLetterListView pickLetterListView = (PickLetterListView) binding.rootLayout.getChildAt(i);
            customFieldListBeans.add(pickLetterListView.getContent());
        }
        getFilterJson();

        if (startType.equals("jj")) {
            viewModel.saveUserInquiryForBid(viewModel.userInquiryForTender.get());
        } else if (startType.equals("jc")) {
            viewModel.saveUserInquiryForJc(viewModel.userInquiryForTender.get());
        } else if ("ZL".equals(startType)) {
            viewModel.addInquery(viewModel.userInquiryForTender.get());
        } else if ("cjjc".equals(startType)) {//供方发起
            viewModel.saveUserInquiryForFactoryJc(viewModel.userInquiryForTender.get());
        } else if ("team".equals(startType)) {
            viewModel.addTeamInquiry(viewModel.userInquiryForTender.get(), teamName);
        } else {
            viewModel.saveUserInquiryForTender(viewModel.userInquiryForTender.get());
        }
    }

    private void getFilterJson() {
        Objects.requireNonNull(viewModel.userInquiryForTender.get()).setMarkId(tenderNo);
//        Objects.requireNonNull(viewModel.userInquiryForTender.get()).setMarkName(binding.cfkTitle.getEditContent() + "");
        Objects.requireNonNull(viewModel.userInquiryForTender.get()).setMarkName(markName);
        Objects.requireNonNull(viewModel.userInquiryForTender.get()).setQuestion(binding.cfkEdit.getEditContent() + "");
        Objects.requireNonNull(viewModel.userInquiryForTender.get()).setComprehend(binding.cfkEdit2View.getEditContent() + "");
        Objects.requireNonNull(viewModel.userInquiryForTender.get()).setRequestAnswer(binding.cfkEdit3View.getEditContent() + "");
        Objects.requireNonNull(viewModel.userInquiryForTender.get()).setCustomFieldList(customFieldListBeans);
        Objects.requireNonNull(viewModel.userInquiryForTender.get()).setFileList(fileImageList);
        Objects.requireNonNull(viewModel.userInquiryForTender.get()).setAnswerUserNo(answerUserNo);
        Objects.requireNonNull(viewModel.userInquiryForTender.get()).setAnswerUserCompanyNo(answerUserCompanyNo);
        Objects.requireNonNull(viewModel.userInquiryForTender.get()).setInquiryUserMemberNo(inquiryUserMemberNo);
        Objects.requireNonNull(viewModel.userInquiryForTender.get()).setMarkType(markType);
        Objects.requireNonNull(viewModel.userInquiryForTender.get()).setModelType(modelType);
        if (tenderingType > 0) {
            Objects.requireNonNull(viewModel.userInquiryForTender.get()).setInquiryType(pickSelectEntityList.get(selectPosition[0]).getNo());
        }
    }

    //图片单张上传
    public void uploadRefresh(String url, int type) {
        uploadImgList.add(url);
        if (currentImgNum + 1 == imgTotal) {
            uploadImgSuccess(uploadImgList, type);
        } else {
            currentImgNum++;
            viewModel.uploadMutiFileModel(adapter.getFileList().get(currentImgNum), 0, currentImgNum + 1);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片结果回调
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                fileList.clear();
                urls.clear();
                for (LocalMedia localMedia : selectList) {
                    File file = new File(localMedia.getRealPath());
                    fileList.add(file);
                    urls.add(localMedia.getRealPath());
                }
                adapter.setDatas(selectList, urls);
                adapter.setFileList(fileList);
            }
        }
    }
}
